package com.xscha.tableforge.service.impl;

import com.xscha.tableforge.model.dto.FieldMetaDto;
import com.xscha.tableforge.model.dto.TableMetaDto;
import com.xscha.tableforge.model.entity.FieldMeta;
import com.xscha.tableforge.model.entity.TableMeta;
import com.xscha.tableforge.model.entity.ViewMeta;
import com.xscha.tableforge.model.vo.PageReq;
import com.xscha.tableforge.model.vo.PageResult;
import com.xscha.tableforge.repository.FieldMetaRepository;
import com.xscha.tableforge.repository.TableMetaRepository;
import com.xscha.tableforge.service.BaseService;
import com.xscha.tableforge.service.TableDataService;
import com.xscha.tableforge.service.TableMetaService;
import com.xscha.tableforge.service.ViewMetaService;
import com.xscha.tableforge.constants.ViewType;
import com.xscha.tableforge.utils.EntityFieldUtil;
import com.xscha.soyue.common.core.utils.BeanMapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 表元数据服务实现类
 */
@Service
public class TableMetaServiceImpl extends BaseService<TableMeta> implements TableMetaService {

    private final TableMetaRepository tableMetaRepository;
    private final FieldMetaRepository fieldMetaRepository;
    private final TableDataService dynamicTableService;
    private final ViewMetaService viewMetaService;

    @Autowired
    public TableMetaServiceImpl(TableMetaRepository tableMetaRepository,
                           FieldMetaRepository fieldMetaRepository,
                           TableDataService dynamicTableService,
                           ViewMetaService viewMetaService) {
        this.tableMetaRepository = tableMetaRepository;
        this.fieldMetaRepository = fieldMetaRepository;
        this.dynamicTableService = dynamicTableService;
        this.viewMetaService = viewMetaService;
    }

    @Override
    public TableMeta findById(String id) {
        return tableMetaRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("表不存在"));
    }

    @Override
    public List<TableMeta> findAllByAppId(String appId) {
        return tableMetaRepository.findAllByAppId(appId);
    }

    @Override
    public PageResult<TableMeta> findPageByAppId(String appId, PageReq pageRequest) {
		PageReq processedReq = processPageRequest(pageRequest);
        return tableMetaRepository.findPageByAppId(appId, processedReq);
    }

    @Override
    @Transactional
    public TableMetaDto createTableMeta(TableMetaDto tableMetaDto, String userId) {
        // 处理字段的dbFieldType和dbFieldName
        if (tableMetaDto.getFields() != null) {
            for (FieldMetaDto field : tableMetaDto.getFields()) {
                // 设置dbFieldType
                if (field.getDbFieldType() == null && field.getType() != null) {
                    field.setDbFieldType(EntityFieldUtil.mapTypeToDbFieldType(field.getType()));
                }
                
                // 设置cellValueType默认值
                if (field.getCellValueType() == null) {
                    field.setCellValueType(EntityFieldUtil.mapTypeToDbFieldType(field.getType()));
                }
                
                // 设置其他默认值
                if (field.getIsMultipleCellValue() == null) field.setIsMultipleCellValue(false);
                if (field.getNotNull() == null) field.setNotNull(false);
                if (field.getIsUnique() == null) field.setIsUnique(false);
                if (field.getIsPrimary() == null) field.setIsPrimary(false);
                if (field.getIsComputed() == null) field.setIsComputed(false);
                if (field.getIsLookup() == null) field.setIsLookup(false);
                if (field.getIsPending() == null) field.setIsPending(false);
                if (field.getHasError() == null) field.setHasError(false);
                if (field.getDisplayOrder() == null) field.setDisplayOrder(0.0);
            }
        }
        
        // 创建表
        TableMetaDto createdTable = dynamicTableService.createTable(tableMetaDto, userId);
        
        // 为新创建的表添加默认的表格视图
        createDefaultGridView(createdTable.getId(), userId);
        
        return createdTable;
    }
    
    @Override
    @Transactional
    public TableMeta updateTableMeta(String id, TableMetaDto tableMetaDto, String userId) {
        TableMeta tableMeta = tableMetaRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("表不存在"));
        
        tableMeta.setName(tableMetaDto.getName());
        tableMeta.setDescription(tableMetaDto.getDescription());
        tableMeta.setIcon(tableMetaDto.getIcon());
        tableMeta.setDisplayOrder(tableMetaDto.getDisplayOrder());
        tableMeta.setVersion(tableMeta.getVersion() + 1);
        tableMeta.setLastModifiedTime(LocalDateTime.now());
        tableMeta.setLastModifiedBy(userId);
        
        return tableMetaRepository.save(tableMeta);
    }

    @Override
    @Transactional
    public void deleteTableMeta(String id, String userId) {
        TableMeta tableMeta = tableMetaRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("表不存在"));
        
        tableMeta.setDeletedTime(LocalDateTime.now());
        tableMeta.setLastModifiedTime(LocalDateTime.now());
        tableMeta.setLastModifiedBy(userId);
        
        tableMetaRepository.save(tableMeta);
    }

    @Override
    public TableMetaDto getTableMetaWithFields(String id) {
        // 获取表元数据
        TableMeta tableMeta = tableMetaRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("表不存在"));
        
        // 获取表的字段信息
        List<FieldMeta> fieldMetas = fieldMetaRepository.findAllByTableId(id);
        
        // 转换为DTO对象
        List<FieldMetaDto> fieldMetaDtos = fieldMetas.stream()
                .map(this::convertToFieldMetaDto)
                .collect(Collectors.toList());
        
        // 创建并返回DTO对象
        TableMetaDto tableMetaDto = new TableMetaDto();
        tableMetaDto.setId(tableMeta.getId());
        tableMetaDto.setName(tableMeta.getName());
        tableMetaDto.setDescription(tableMeta.getDescription());
        tableMetaDto.setAppId(tableMeta.getAppId());
        tableMetaDto.setIcon(tableMeta.getIcon());
        tableMetaDto.setDisplayOrder(tableMeta.getDisplayOrder());
        
        tableMetaDto.setFields(fieldMetaDtos);
        
        return tableMetaDto;
    }
    
    /**
     * 将FieldMeta实体转换为FieldMetaDto
     *
     * @param fieldMeta 字段元数据实体
     * @return 字段元数据DTO
     */
    private FieldMetaDto convertToFieldMetaDto(FieldMeta fieldMeta) {
        FieldMetaDto dto = new FieldMetaDto();
        return BeanMapperUtils.map(fieldMeta, dto);
    }

	@Override
	protected Class<TableMeta> getEntityClass() {
		return TableMeta.class;
	}

    /**
     * 创建默认的表格视图
     * @param tableId 表格ID
     * @param userId 用户ID
     */
    private void createDefaultGridView(String tableId, String userId) {
        try {
            ViewMeta defaultView = new ViewMeta();
            defaultView.setTableId(tableId);
            defaultView.setName("默认表格视图");
            defaultView.setType(ViewType.GRID.getCode());
            defaultView.setIsDefault(true);
            // 设置其他必要的默认属性
            
            viewMetaService.createView(defaultView, userId);
        } catch (Exception e) {
            // 记录异常但不影响表格创建的返回结果
            // 实际项目中应该有更好的错误处理和日志记录
            throw new RuntimeException("创建默认视图失败: " + e.getMessage(), e);
        }
    }
}